/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.agent.service;

import cn.ac.iie.agent.tools.FileTools;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;

/**
 *
 * @author dell
 */
public class FtpUploadJsonFilesThread implements Runnable {

    private static Logger logger = Logger.getLogger(FtpUploadJsonFilesThread.class);
    String subjobid;
    List<String> jsonreturnFlag;
    String jsonFileName;
    String localPath;
    String localErrorPath;
    String localNamespace;
    String src;

    public FtpUploadJsonFilesThread(String subjobid, List<String> jsonreturnFlag, String jsonFileName, String localPath, String localErrorPath, String localNamespace) {
        this.subjobid = subjobid;
        this.jsonreturnFlag = jsonreturnFlag;
        this.jsonFileName = jsonFileName;
        this.localPath = localPath;
        this.localErrorPath = localErrorPath;
        this.localNamespace = localNamespace;
    }

    @Override
    public void run() {
        FileTools fileTools = new FileTools();
        List<String[]> errMsglist = new ArrayList<String[]>();
        List<String> execute = new ArrayList<String>();

        logger.info(subjobid + " start to analyze the JSON file: " + localPath + "Ctrl/" + jsonFileName);
        List<Map<String, String>> dataFileList = null;
        List<Map<String, String>> ftpList = null;

        //解析JSON文件,获取数据文件名
        boolean analyzeFlag = false;
        String jsonString = fileTools.readFileByStream(localPath + "Ctrl/" + jsonFileName);
        try {
            dataFileList = parseJson(jsonString, "file_list");
            ftpList = parseJson(jsonString, "ftp_list");
            if (dataFileList.isEmpty() || ftpList.isEmpty()) {
                //错误信息添加进errMsglist
                String[] message = {jsonFileName, "2"};
                errMsglist.add(message);
            } else {
                analyzeFlag = true;
            }
        } catch (Exception e) {
            logger.error(subjobid + " analyze the JSON file:" + localPath + "Ctrl/" + jsonFileName + " failed!cause: " + e.getMessage(), e);
            String[] message = {jsonFileName, "2"};
            errMsglist.add(message);
        }

        if (analyzeFlag) {
            //数据文件上传给不同ftp
            for (int i = 0; i < ftpList.size(); i++) {
                HashMap ftp = (HashMap) ftpList.get(i);
                new FtpUploadDataFilesThread(subjobid, jsonFileName, localPath, dataFileList, ftp, errMsglist, execute).run();
            }
        }

        String returnFlag = "";
        if (!execute.isEmpty()) {
            for (String f : execute) {
                returnFlag += f + ",";
            }
        }

        if (!returnFlag.contains("true") || !analyzeFlag) {
            File errDir = new File(localErrorPath);
            if (!errDir.exists()) {
                errDir.mkdir();
            }

            String str = "";
            String errMsg = "\"src\":\"" + src + "\",\"file_list\":[";
            if (!errMsglist.isEmpty()) {
                for (int j = 0; j < errMsglist.size(); j++) {
                    str = str + "{\"name\":\"" + errMsglist.get(j)[0] + "\",\"code\":\"" + errMsglist.get(j)[1] + "\"}" + ",";
                }
                errMsg = "{" + errMsg + str.substring(0, str.length() - 1) + "]}";
                logger.info(subjobid + " write error JSON file: Err_" + jsonFileName + ", and message is: " + errMsg);
                fileTools.mkFile(localErrorPath, "/Err_" + jsonFileName, errMsg);
                fileTools.mkFile(localErrorPath + "/Err_" + jsonFileName + ".ok", "ok");
                logger.info(subjobid + " create dwd file, and the filename is: " + localPath + jsonFileName + "." + localNamespace + ".dwd");
                fileTools.mkFile(localPath + "Ctrl/" + jsonFileName + "." + localNamespace + ".dwd", "ok");
            }
        } else if (!returnFlag.contains("false") && analyzeFlag) {
            //所有都成功，本地dwd
            logger.info(subjobid + " create dwd file, and the filename is: " + localPath + jsonFileName + "." + localNamespace + ".dwd");
            fileTools.mkFile(localPath + "Ctrl/" + jsonFileName + "." + localNamespace + ".dwd", "ok");
        }

        if (!returnFlag.isEmpty()) {
            if (!returnFlag.contains("false")) {
                jsonreturnFlag.add("true");
            } else {
                jsonreturnFlag.add("false");
            }
        } else {
            jsonreturnFlag.add("false");
        }
    }

    public List<Map<String, String>> parseJson(String jsonString, String nameNode) {
        //parseJsonString
        JSONObject jsonObject = JSONObject.fromObject(jsonString);
        src = jsonObject.get("src").toString();
        JSONArray jsonArray = jsonObject.getJSONArray(nameNode);
        List<Map<String, String>> rsList = new ArrayList<Map<String, String>>();
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject object = (JSONObject) jsonArray.get(i);
            Map<String, String> map = new HashMap<String, String>();
            for (Iterator<?> iter = object.keys(); iter.hasNext();) {
                String key = (String) iter.next();
                String value = object.get(key).toString();
                map.put(key, value);
            }
            rsList.add(map);
        }
        return rsList;
    }

}
